import 'dart:io';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/push/jpush_utils.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 权限管理
class PermissionManager {
  /// 请求权限
  /// [permission] 权限
  /// [msg] 未授权时的提示信息
  /// return [true] 已授权 [false] 未授权
  static Future<bool> requestPermission(Permission permission, {String msg = ''}) async {
    var status = await permission.status;
    if (status.isDenied || status.isPermanentlyDenied) {
      status = await permission.request();
      if (status.isDenied || status.isPermanentlyDenied) {
        if (msg.isNotEmpty) {
          ToastUtils.showToast(msg);
        }
        return Future.value(false);
      }
    }
    return Future.value(true);
  }

  /// 动态申请定位权限
  static void requestLocationPermissions(BuildContext context, {Function()? onPermissionDenied, Function? success}) async {
    // 为了上架，做一些处理，提示授权
    final prefs = await SharedPreferences.getInstance();

    if (Platform.isAndroid) {
      var status = await Permission.location.status;
      XLogger.info(status);
      if (status.isDenied || status.isPermanentlyDenied) {
        if (prefs.getString('locationisDenied') != null) {
          // onPermissionDenied?.call();
          // ToastUtils.showToast('请到设置中打开定位权限');

        } else {

          requestPermissionDialog(context, title: '提示', msg: '为了提供基于您当前位置的服务，我们需要您的许可来获取位置信息。', cancelAction: () {
            // 取消
            context.pop();
          }, confirmAction: () async {
            status = await Permission.location.request();
            XLogger.info('requestLocationPermission status: $status');
            // 确定
            if (status == PermissionStatus.granted) {
              // 权限申请通过
              success?.call();
            } else {

              // 权限申请未通过
              await prefs.setString('locationisDenied', 'locationisDenied');
              // onPermissionDenied?.call();
            }
            context.pop();
          });
        }

      }
      return;
    }
    // iOS
    bool hasLocationPermission = await requestLocationPermission();
    XLogger.info('hasLocationPermission: $hasLocationPermission');
    if (hasLocationPermission) {
      // 权限申请通过
    } else {
      // 权限申请未通过
      onPermissionDenied?.call();
    }
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  static Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      XLogger.info('requestLocationPermission status: $status');
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  /// 申请通知权限
  static Future<bool> requestNotificationPermissions() async {
    if (Platform.isAndroid) {
      JPushUtils.requestAndroidPermission();
      return true;
    }
    JPushUtils.requestIOSPermission();
    //获取当前的权限
    var status = await Permission.notification.status;
    if (status == PermissionStatus.granted) {
      JPushUtils.requestIOSPermission();
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.notification.request();
      if (status == PermissionStatus.granted) {
        JPushUtils.requestIOSPermission();
        return true;
      } else {
        return false;
      }
    }
  }

  /// 申请权限弹窗
  static void requestPermissionDialog(BuildContext context,
      {String title = '提示', String msg = '', VoidCallback? cancelAction, VoidCallback? confirmAction}) {
    /// 自定义一个弹窗
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
        return TDAlertDialog(
          title: title,
          content: msg,
          leftBtn: TDDialogButtonOptions(
              title: '取消',
              action: () {
                cancelAction?.call();
              },
              titleColor: AppTheme.themeConfig.infoTextColor),
          rightBtn: TDDialogButtonOptions(
              title: '确定',
              action: () {
                confirmAction?.call();
              },
              titleColor: Colors.white,
              style: TDButtonStyle(
                backgroundColor: AppTheme.themeConfig.primaryColor,
              )),
        );
      },
    );
  }

  static void openSettings() {
    openAppSettings();
  }
}
